<?php

namespace App\Admin\Forms;

use App\Models\WxTenant;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Cache;

class ImportRobotUserForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $names = $input['names'];
        $num = $input['num'];
        $tenant = $input['tenant'];
        if(_empty_($tenant)){
            $tenant = 0;
        }

        $cosv5 = Settings::get('cosv5', []);
        $img_domain = $cosv5['domain'];


        if (Cache::has('ImportRobotUserForm')){
            Cache::forget('ImportRobotUserForm');
            return $this->response()
                ->warning('请勿重复点击，有任务还在运行中');
        }

        if(_empty_($names)){
            if(!file_exists(storage_path('bilibili_user_info.csv'))){
                return $this->response()
                    ->warning('不存在：bilibili_user_info.json，请先上传该文件到服务器');
            }

            Cache::put('ImportRobotUserForm', 1, 180);

            $cursor = Settings::get('bilibili_user_info_cursor', 0);
            set_time_limit(100000);
            $str_arr = explode("\n", file_get_contents(storage_path('bilibili_user_info.csv')));


            for ($i = 0; $i < $num; $i ++){
                $row_arr = explode(',', $str_arr[$cursor]);
                $name = $row_arr[2];
                if($name){
                    $avatar = $img_domain.'/avatars/'.mini_rand(0, 14602).'.png';
                    $sex = 0;
                    if(trim($row_arr[3]) == '男'){
                        $sex = 1;
                    }else if(trim($row_arr[3]) == '女'){
                        $sex = 2;
                    }
                    UserUtils::insert_null_user($name, $avatar, $sex, $tenant);
                }
                $cursor ++;
            }
            Settings::set('bilibili_user_info_cursor', $cursor);
            Cache::forget('ImportRobotUserForm');
            return $this->response()
                ->success('成功导入'.$num.'个机器人')->refresh();
        }else{
            $name_arr = explode('|', $names);
            if($name_arr){
                foreach ($name_arr as $name){
                    if($name){
                        $avatar = $img_domain.'/avatars/'.mini_rand(0, 14602).'.png';
                        $sex = 0;
                        UserUtils::insert_null_user($name, $avatar, $sex, $tenant);
                    }
                }
                Cache::forget('ImportRobotUserForm');
                return $this->response()
                    ->success('成功导入'.count($name_arr).'个机器人')->refresh();
            }
        }
    }

    public function form()
    {
        $this->html(function () {
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">注意注意注意：导入机器人前，务必看操作教程：<a href="https://doc.minisns.cn/doc/115/" target="_blank" >https://doc.minisns.cn/doc/115/</a></div>';
        }, '');
        $this->number('num', '导入数量')->max(2000)->required();
        $this->textarea('names', '用户名')->help('用竖号隔开，列如：张三|李四，可以不填，因为我爬了b站90w的用户名，作为库存');
        $this->select('tenant', '站点')->options(WxTenant::pluck('name', 'tenant_id'))->default(0);
    }
}
